class RRD
  def initialize(rrd_name,vertical_label="test")
    @rrd_name = rrd_name
    @vertical_label = vertical_label
  end
  def create(interval)
    interval = interval.to_s
    interval_mins = (interval.to_f)/60
    heartbeat = ((interval.to_i)*2).to_s
    ds_string = " DS:test:GAUGE:#{heartbeat}:U:U"
    cmd_create = ["rrdtool create ", @rrd_name, " --step ", interval, ds_string,
                  " RRA:AVERAGE:0.5:1:", ((4000/interval_mins).to_i).to_s, 
                  " RRA:AVERAGE:0.5:", ((30/interval_mins).to_i).to_s, ":800",
                  " RRA:AVERAGE:0.5:", ((120/interval_mins).to_i).to_s, ":800",
                  " RRA:AVERAGE:0.5:", ((1440/interval_mins).to_i).to_s, ":800"].join('')
    puts cmd_create
    cmd_out = system("#{cmd_create}")
    raise(RRDException, "Unable to create RRD") unless cmd_out
  end
  def update(*values)
    values_args = values.join(':')
    cmd_update = "rrdtool update #{@rrd_name} N:#{values_args}"
    puts cmd_update
    cmd_out = system("#{cmd_update}")
    raise(RRDException, "Unable to update RRD") unless cmd_out
  end
  def graph(mins)
    start_time = "now-#{mins*60}"
    output_filename = @rrd_name + '.png'
    end_time = 'now'
    ds_name = 'test'
    width = '400'
    height = '150'
    cur_date = Time.now.strftime("%m/%d/%Y %H\\\:%M\\\:%S")
    cmd_graph = 'rrdtool graph ' + output_filename + \
        ' DEF:' + ds_name + '=' + @rrd_name + ':' + ds_name + ':AVERAGE' + \
        ' AREA:' + ds_name + '#FF0000' + \
        ' VDEF:' + ds_name + 'last=' + ds_name + ',LAST' + \
        ' VDEF:' + ds_name + 'avg=' + ds_name + ',AVERAGE' + \
        ' COMMENT:"' + cur_date + '"' + \
        ' GPRINT:' + ds_name + 'avg:"                         average=%6.2lf%S"' + \
        ' --title="' + @rrd_name +'"' + \
        ' --vertical-label="' + @vertical_label + '"' \
        ' --start=' + start_time + \
        ' --end=' + end_time + \
        ' --width=' + width + \
        ' --height=' + height + \
        ' --lower-limit="0"'
    puts cmd_graph
    cmd_out = system("#{cmd_graph}")
    raise(RRDException, "Unable to write to RRD") unless cmd_out
  end
end

class RRDException < RuntimeError
end